﻿using MSDIS.Configuration.DAO;
using MSDIS.Configuration.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MSDIS.Configuration
{
    public class ConfigurationService : IConfigurationService
    {
        private VariableDao variableDao;
        private static string DATETIME_FORMAT = "dd MMM yyyy HH:mm:ss";

        public ConfigurationService()
        {
            variableDao = new VariableDao();
        }

        public IVariable GetVariableByName(string name)
        {
            VariableEntity entity = variableDao.GetVariables().SingleOrDefault(e => e.Name == name);

            IVariable variable = new Variable() { Id = entity.Id, Name = entity.Name, DefaultValue = Utils.GetValue(entity.DefaultValue), Value = Utils.GetValue(entity.Value), Type = Type.GetType(entity.Type), LastUpdated = entity.LastUpdated };

            return variable;
        }

        public void CreateVariable(IVariable variable)
        {
            VariableEntity entity = new VariableEntity();

            entity.Name = variable.Name;
            entity.Value = Utils.GetValueAsBinary(variable.Value);
            entity.DefaultValue = Utils.GetValueAsBinary(variable.DefaultValue);
            entity.Type = variable.Type.AssemblyQualifiedName;
            entity.LastUpdated = DateTime.Now.ToString(DATETIME_FORMAT);

            variableDao.Add(entity);

            variable.Id = entity.Id;
            variable.LastUpdated = entity.LastUpdated;
        }

        public void UpdateVariable(IVariable variable)
        {
            VariableEntity entity = variableDao.GetVariableById(variable.Id);

            entity.Name = variable.Name;
            entity.Value = Utils.GetValueAsBinary(variable.Value);
            entity.DefaultValue = Utils.GetValueAsBinary(variable.DefaultValue);
            entity.LastUpdated = DateTime.Now.ToString(DATETIME_FORMAT);

            variableDao.Update(entity);
        }

        public void DeleteVariable(int id)
        {
            variableDao.Delete(id);
        }
    }
}
